package com.meirengu.webview.controller;

import com.alibaba.fastjson.JSONObject;
import com.meirengu.channel.service.RongziService;
import com.meirengu.channel.service.YiCaiDaoService;
import com.meirengu.common.RedisClient;
import com.meirengu.utils.HttpUtil;
import com.meirengu.utils.RequestUtil;
import com.meirengu.webview.model.KwTest;
import com.meirengu.webview.model.User;
import com.meirengu.webview.model.UserInfo;
import com.meirengu.webview.service.*;
import com.meirengu.webview.utils.ConfigUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StopWatch;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.PrintWriter;
import java.util.*;

/**
 * ${DESCRIPTION}
 *
 * @author Mao
 * @create 2017-12-19 12:27
 */
@Controller
@RequestMapping("test")
public class TestController {

    @Autowired
    YiCaiDaoService yiCaiDaoService;

    @Autowired
    UserInfoService userInfoService;

    @Autowired
    KwUserErrorService kwUserErrorService;

    @Autowired
    UserService userService;

    @Autowired
    RedisClient redisClient;

    @Autowired
    RongziService rongziService;

    @Autowired
    private KwTestService kwTestService;

    @Autowired
    private LmUserBaseService lmUserBaseService;

    Logger logger = LoggerFactory.getLogger(TestController.class);


    @RequestMapping("test")
    public void test(HttpServletRequest request) {
        yiCaiDaoService.reg("", "李思敏", "1", "18813099929", "1989-01", "北京市", "20", "1", "1", "1", "1", "1", "4", "3", "2", "", "1");
    }

    @RequestMapping("testRedisSet")
    public void testRedisSet(HttpServletRequest request) {
        Set<String> set = new HashSet<String>();
        List<Map<String, Object>> lmUserBaseList = lmUserBaseService.getList(new HashMap<>());
        if (lmUserBaseList != null && lmUserBaseList.size() > 0) {
            for (Map<String, Object> map : lmUserBaseList) {
                String mobile = map.get("phone").toString();
                set.add(mobile);

            }
        }
        List<Map<String, Object>> kwUserList = userService.getAllMobile(new HashMap<>());
        if (kwUserList != null && kwUserList.size() > 0) {
            for (Map<String, Object> map : kwUserList) {
                String mobile = map.get("mobile").toString();
                set.add(mobile);
            }
            redisClient.sadd("kwdRegister", set);
        }

    }

    @RequestMapping("setRedisClient")
    public void setRedisClient(HttpServletRequest request) {
        Set<String> set = new HashSet<>();
        Map<String, Object> map = new HashMap<>();
        map.put("createTimeBegin", "2018-07-19 21:00:00");
        map.put("createTimeEnd", "2018-07-19 22:00:00");
        List<Map<String, Object>> kwUserList = userService.getList(map);
        if (kwUserList != null && kwUserList.size() > 0) {
            for (Map<String, Object> mobileMap : kwUserList) {
                String mobile = mobileMap.get("mobile").toString();
                set.add(mobile);
            }
            redisClient.sadd("kwdRegister", set);
        }

    }

    @RequestMapping("setRemove")
    public void setRemove(HttpServletRequest request) {
        Set<String> set = new HashSet<>();
        List<Map<String, Object>> kwUserList = userService.getAllMobile(new HashMap<>());
        if (kwUserList != null && kwUserList.size() > 0) {
            for (Map<String, Object> map : kwUserList) {
                String mobile = map.get("mobile").toString();
                set.add(mobile);
            }
        }
        Set<String> redisSet = redisClient.smembers("kwdRegister");
        Set<String> result = new HashSet<String>();
        result.clear();
        result.addAll(set);
        result.removeAll(redisSet);
        System.out.println("差集：" + result);

    }

    @RequestMapping("testRedisSetQuery")
    public void testRedisSetQuery(@RequestParam(value = "mobile", defaultValue = "15835132986", required = false) String mobile) {
        boolean flag = false;
        StopWatch watch = new StopWatch();
        watch.start();
        try {
            flag = redisClient.sismember("kwdregister", mobile);
        } finally {
            watch.stop();
            logger.debug("query:" + mobile + ":time" + watch.getTotalTimeMillis());
        }
        System.out.println(flag);

    }

    @RequestMapping("testRedisSetQueryAll")
    public void testRedisSetQueryAll() {
        List<Map<String, Object>> kwUserErrorList = kwUserErrorService.getList(new HashMap<>());
        if (kwUserErrorList != null && kwUserErrorList.size() > 0) {
            StopWatch watch = new StopWatch();
            watch.start();
            try {
                for (Map<String, Object> map : kwUserErrorList) {
                    String mobile = map.get("mobile").toString();
                    boolean flag = redisClient.sismember("kwdregister", mobile);
                    if (!flag) {
                        System.out.println(flag);
                    }
                }
            } finally {
                watch.stop();
                logger.debug("query:" + ":time" + watch.getTotalTimeMillis());
            }
        }


    }


    public JSONObject httpRequest(String url, Map<String, String> params) {
        logger.info("==NiWoDaiServiceImpl.httpRequest url:{}, params:{}", url, params);
        HttpUtil.HttpResult hr = HttpUtil.doPostForm(url, params);
        int code = hr.getStatusCode();
        if (code == 200) {
            logger.info("==NiWoDaiServiceImpl.httpRequest http request success. result:{}", hr.toString());
            String content = hr.getContent();
            JSONObject returnMsg = JSONObject.parseObject(content);
            return returnMsg;
        } else {
            logger.warn("==NiWoDaiServiceImpl.httpRequest http requesst fail. code:{}, result:{}", code, hr.toString());
            return null;
        }
    }

    @RequestMapping("testRongziIsRegister")
    public void testRongziIsRegister(@RequestParam(value = "mobile", defaultValue = "15835132986", required = true) String mobile) throws Exception {
        String subchannel = ConfigUtil.getConfig("北京");
//      ongziService.registered(mobile);
    }

    @RequestMapping("testPinganZX")
    public void testPinganZX(@RequestParam(value = "mobile", defaultValue = "15835132986", required = true) String mobile) throws Exception {
        //查出符合条件的用户
        Map<String, Object> map = new HashMap<>();
        List<Map<String, Object>> userList = userService.getList(map);
        userList = userService.getList(map);
        if (userList != null && userList.size() > 0) {
            for (Map<String, Object> userMap : userList) {
                String id = userMap.get("id").toString();
                UserInfo userInfo = userInfoService.getByUserId(id);
                if (userInfo != null && StringUtils.isNotBlank(userInfo.getId())) {
                    User user = new User();
                    user.setId(id);
                    user.setName(userMap.get("name").toString());
                    user.setMobile(userMap.get("mobile").toString());
                    user.setSex(Integer.parseInt(userMap.get("sex").toString()));
                    userInfoService.sendPingAnZX(userInfo, user);
                }
            }
        }
    }

    @RequestMapping("testClientIp")
    public String testClientIp(HttpServletRequest request) throws Exception {
        String ip = RequestUtil.getClientIp(request);
        return ip;
    }

    /**
     * 发送信贷员数据
     */
    @ResponseBody
    @RequestMapping("/sendProduct")
    public void sendProduct(@RequestParam(value = "createTimeBegin", required = true) String createTimeBegin,
                            @RequestParam(value = "createTimeEnd", required = true) String createTimeEnd) throws Exception {
        //查出符合条件的用户
        Map<String, Object> map = new HashMap<>();
        if (StringUtils.isNotBlank(createTimeBegin)) {
            map.put("createTimeBegin", createTimeBegin);
        }
        if (StringUtils.isNotBlank(createTimeEnd)) {
            map.put("createTimeEnd", createTimeEnd);
        }
        List<Map<String, Object>> userList = userService.getList(map);
        if (userList != null && userList.size() > 0) {
            for (Map<String, Object> userMap : userList) {
                String id = userMap.get("id").toString();
                UserInfo userInfo = userInfoService.getByUserId(id);
                if (userInfo != null && StringUtils.isNotBlank(userInfo.getId())) {
                    User user = new User();
                    user.setId(id);
                    user.setName(userMap.get("name").toString());
                    user.setMobile(userMap.get("mobile").toString());
                    user.setSex(Integer.parseInt(userMap.get("sex").toString()));
                    userInfoService.sendProduct(user, userInfo);
                }
            }
        }
    }


    @RequestMapping("ppdToken")
    public void ppdToken(@RequestParam(value = "code", required = true) String code) {
        System.out.println(code);
    }

    @RequestMapping("testtestRedisredis")
    public void testRedis(HttpServletRequest request) {
        userInfoService.testRedis();
    }


    @RequestMapping("testUUID")
    public void testUUID(HttpServletRequest request) {
        File file = new File("/Users/lx/Desktop/32gw2_081518.txt");
        BufferedReader reader = null;
        String temp = null;
        int line = 1;
        KwTest kwTest = null;
        List<KwTest> list = new ArrayList<KwTest>();
        try {
            reader = new BufferedReader(new FileReader(file));
            while ((temp = reader.readLine()) != null) {
                System.out.println("line" + line + ":" + temp);
                String[] strArr = temp.split(",");
                String dateStr = strArr[0];
                Date date = DateUtils.parseDate(dateStr, "yyyy-MM-dd HH:mm:ss");
                String mobile = strArr[1];
                String statusStr = strArr[2];
                Integer status = Integer.parseInt(statusStr);
                String content = strArr[3];
                kwTest = new KwTest();
                kwTest.setSendDate(date);
                kwTest.setMobile(mobile);
                kwTest.setStatus(status);
                kwTest.setContent(content);
                list.add(kwTest);
                line++;

            }
            //如果大于1W条，则每次只存1W
            int i = 1;
            int num = 10000;
            int k = 0;//成功保存的条数
            while ((i * num) < list.size()) {
                k += kwTestService.batchSave(list.subList(((i - 1) * num), (i * num)));
                i++;
            }
            k += kwTestService.batchSave(list.subList(((i - 1) * num), list.size()));
            logger.info("数据成功保存" + k + "条");
            /*Iterator it = lineSet.iterator();
            while (it.hasNext()) {
                System.out.println(it.next());
            }*/
            /*for (Map.Entry<String, Integer> entry : map.entrySet()) {
                System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
            }*/

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }


    }

    @RequestMapping("testHttp")
    public void testUUID(HttpServletRequest request, HttpServletResponse response) throws Exception {

    }

}
